package minderupt.selenate.translate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;

/**
 *
 */
public class CachedDTDResolver implements EntityResolver {

    public static final String XHTML_DTD = "xhtml1-strict.dtd";
    public static final String XHTML_LAT1 = "xhtml-lat1.ent";
    public static final String XHTML_SYMBOL = "xhtml-symbol.ent";
    public static final String XHTML_SPECIAL = "xhtml-special.ent";
    
    private static Log LOGGER = LogFactory.getLog(CachedDTDResolver.class);


    @Override
    public InputSource resolveEntity(String head, String resource) throws SAXException, IOException {

        String resourceName = resource.substring(resource.lastIndexOf("/") + 1);
        if(LOGGER.isDebugEnabled()) LOGGER.debug("Resolving:  " + resourceName);

        InputStream uri = null;
        if (resourceName.equals(XHTML_DTD)) {
            uri = this.getClass().getResourceAsStream("/dtd/" + XHTML_DTD);
        } else if (resourceName.equals(XHTML_LAT1)) {
            uri = this.getClass().getResourceAsStream("/dtd/" + XHTML_LAT1);
        } else if (resourceName.equals(XHTML_SYMBOL)) {
            uri = this.getClass().getResourceAsStream("/dtd/" + XHTML_SYMBOL);
        } else if (resourceName.equals(XHTML_SPECIAL)) {
            uri = this.getClass().getResourceAsStream("/dtd/" + XHTML_SPECIAL);
        } else {
            if(LOGGER.isDebugEnabled()) LOGGER.debug("Not matching any special xhtml entities.");
            return null;
        }

        if(LOGGER.isDebugEnabled()) LOGGER.debug("Resolved.");
        return new InputSource(uri);


    }
}
